﻿// JavaScript Document
var userid = "";
var checkNameResult = -1;
$(function() {
	/*每个金额按钮的点击事件，将按钮的金额显示在支付金额的框里*/
	$(".chg-jine li").click(function() {
		$(this).addClass("chg-jine-active").siblings().removeClass("chg-jine-active");
		var styName = $(this).text();
		$(".chg-xianshi-num span").html(styName);
		$(".chg-xianshi-num font").hide();
	});

	//其他金额输入框获取焦点事件
	$(".chg-jine-other input").focus(function() {
		$(this).css({"width": "80%"});
		//获取到input上面的li
		$(this).parent().parent().addClass("chg-jdzt");
		if (this.value == '') {
			// this.value = '';
			//显示那个“元”
			$(".chg-jdzt span").show();
		}
		//“只能输入10的倍数”显示出来
		$(".chg-xianshi-only").show();
	});
	//其他金额输入框失去焦点事件
	$(".chg-jine-other input").blur(function() {
		$(this).css({"width": "100%"});
		if (this.value == '') {
			// this.value = '其他金额';
			//隐藏那个“元”
			$(".chg-jdzt span").hide();
		}
		//“只能输入10的倍数”隐藏
		$(".chg-xianshi-only").hide();
		var styNamea = $(this).val();
		$(".chg-xianshi-num span").html(styNamea);
		//校验输入的金额是否正确
		jine_check(10, 500);
	});

	$("#phone").on({
		"keypress": function(e) {
			var phoneNo = $(this).val();
			if(e.keyCode !== 8) {
				if(phoneNo.length === 3) {
					$(this).val(phoneNo + " ");
				}
				if(phoneNo.length === 8) {
					$(this).val(phoneNo + " ");
				}
			} 
			
		},
		"keyup": function(e) {
			var phoneNo = $(this).val();
			if(e.keyCode === 8) {
				if(phoneNo.length === 9) {
					$(this).val(phoneNo.trim());
				}
				if(phoneNo.length === 4) {
					$(this).val(phoneNo.trim());
				}
			}
		}
	});
});

function showTip(content) {
	document.getElementById("chg-bussy").style.display = "block";
	document.getElementById("chg-bussy").innerHTML = content;
}

function clearJine() {
	$(".chg-xianshi-num span").html("");
	$(".chg-jine-other input").val("");
	$(".chg-jdzt span").hide();
}
//充值金额大小校验
function jine_check(min, max) {
	var val_obj = $(".chg-xianshi-num span").html();
	var msg = '';
	if (!isNaN(val_obj)) {
		var val = parseInt(val_obj);
		if (val < min || val > max) {
			msg = '请输入' + min + '和' + max + '之间的整数！';
			clearJine();
		} else {
			var val_ = val % 10;
			if (val_ != 0) {
				msg = '请输入' + min + '和' + max + '之间10的倍数';
				clearJine();
			} else {
				//正常的数字
				$(".chg-xianshi-num font").show();
			}
		}
	} else {
		msg = '请输入' + min + '和' + max + '之间的整数！';
		clearJine();
	}
	if (msg != '') {
		showTip(msg);
		sj2();
	}
}

//初始化将URL上的参数值放到页面中的元素中去，其实就是一个传参的作用，另外调用后端生成一个订单号
function init() {
	var params = {
		"userId": getParamValue("userId"),
		"fxstr": getParamValue("fxstr")
	}; //以后來自于URL参数
	$.ajax({
		type: "POST",
		url: "../recharge/genOrderId",
		data: params, //以后來自于URL参数
		dataType: "json",
		success: function(resdata) {
			// console.log(resdata);
			if(!resdata){
				alert("获取订单号失败！");
				return;
			}else if(resdata.resultCode !== 1000){
				alert(resdata.message);
				return;
			}
			var data = resdata.data;
			$("#orderid").html(data.orderId);
			$("#orgName").val(data.orgName);

			if (data.userid) {
				userid = data.userid;
			}
		}
	});
	$(".chg-xianshi").css("line-height", "265%");
	var url = document.location.href;
	//解析参数，放入隐藏的input里面。
}

//立即充值
function submitOrder() {
	var yzm = $('#randcode').val();
	if (yzm == null || yzm.length < 4) {
		showTip("请输入正确的验证码");
		sj2();
		return;
	}
	var $phone = $('#phone');

	checknew_submit($phone, Constants.cmccMobileReg);
}

//显示两秒
function sj2() {
	var count = 2;
	countdown = setInterval(function() {
		if (count == 0) {
			document.getElementById("chg-bussy").style.display = "none";
		}
		count--;
	}, 1000);
}

//充值手机号状态校验
function checknew_submit($obj, patt) {
	if (!regularCheck($obj.val().replace(/\s/g, ''), Constants.cmccMobileReg)) { //
		showTip("请输入正确的四川移动手机号");
		document.getElementById("phone").focus();
		sj2();
		return;
	}
	if ($obj.val().replace(/\s/g, '').length >= 11) {
		if (!regularCheck($obj.val().replace(/\s/g, ''), patt)) {
			showTip("请输入正确的四川移动手机号");
			document.getElementById("phone").focus();
			sj2();
			return;
		} else {
			verifyRechargePhoneNo();
		}
	} else {
		showTip("请输入正确的四川移动手机号");
		document.getElementById("phone").focus();
		sj2();
		return;
	}
}

/*//校验电话号码是否合法
function verifyRechargePhoneNo(){
	var phoneNo = $('#phone').val();
	var url = "../govGroupH5/dprRequest?uri="+encodeURIComponent("/system/sQUserBase.json?phone_no="+phoneNo);
	console.log("url="+url);
	$.ajax({
		type: "post",
		url: url,
		dataType: "json",
		headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
			console.info(data);
			if (data.resCode == '0000000') {
				console.log('校验成功，开始支付流程');
				//查询当前用户输入的手机号码的实名认证姓名并显示
				checkName(phoneNo);

			} else {
				var msg = data.detailMsg;
				if(typeof(msg)  == "undefined" || msg.length == 0){
					msg = data.resMsg;
				}
				showTip(msg);
				sj2();
			}			
		},
		error: function(textStatus) {
			showTip('服务器请求失败，请联系管理员！');
			sj2();			
			console.info(textStatus);
		}
	});
}*/



//校验电话号码是否合法
function verifyRechargePhoneNo(){
	var phoneNo = $('#phone').val().replace(/\s/g, '');
	var url = Constants.apiV2HostRest + "sQUserBase?token="+getToken();
	console.log("url===================================="+url);
	var params = {
		"BODY":{
			"MASTER_SERV_ID":"1001",
			"PHONE_NO":phoneNo
		}
	};
	var param = JSON.stringify(params);
	$.ajax({
		type: "POST",
		url: url,
		data: param,
		contentType: "application/json",
		dataType: "json",
		headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
			console.info(data);

			if (data.ROOT.RETURN_CODE == '0') {
				console.log('校验成功，开始支付前流程');
				//查询当前用户输入的手机号码的实名认证姓名并显示
				checkName(phoneNo);

			} else if(data.ROOT.RETURN_CODE == '1005'){
				var msg = data.ROOT.RETURN_MSG;
				if(typeof(msg)  == "undefined" || msg.length == 0){
					msg = data.resMsg;
				}
				var jsonStr = JSON.stringify(data);
				if(jsonStr.indexOf("timed out")!=-1 || jsonStr.indexOf("CRM_TEMPLATE")!=-1 || jsonStr.indexOf("中间件")!=-1){
					msg = "调用服务超时，请稍后再试。";
				}else if(jsonStr.indexOf("路由信息")!=-1){
					msg = "非四川移动用户，请确认号码是否正确。";
				}
				showTip(msg);
				sj2();
			} else {
				var msg = data.ROOT.RETURN_MSG;
				if(typeof(msg)  == "undefined" || msg.length == 0){
					msg = data.resMsg;
				}
				showTip(msg);
				sj2();
			}
		},
		error: function(textStatus) {
			showTip('服务器请求失败，请联系管理员！');
			sj2();
			console.info(textStatus);
		}
	});
}



var checkName = function(phone){
	checkNameResult = -1;
	var params = {
		phoneNo: phone
	};
	console.log(params);
	var url = "../broadbandH5/custRealChk";
	$.ajax({
		type: "post",
		url: url,
		data: params,
		dataType: "json",
		async:false,
		headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
			// data = data.ROOT;
			if (data && data.ROOT.RETURN_CODE == 0) {
				// console.log(data);
				var realAccount = $(".chg-xianshi-num span").html();
				if (realAccount.indexOf("元") >= 0) {
					var size = realAccount.length;
					realAccount = realAccount.substring(0, size - 1);
				}
				if (data.ROOT.OUT_DATA.REAL_FLAG == "Y") {
					//保存认证信息
					custIDCard = data.ROOT.OUT_DATA.ID_ICCID;
					// console.log("custIDCard=" + custIDCard);
					custName = data.ROOT.OUT_DATA.CUST_NAME;
					if(custName!=null){
						custName = "*"+custName.substr(1);
					}
					var content = "您正在为<span style='color: red'>"+custName+"</span>充值,金额:<span style='color: red'>"+realAccount+"</span>元，确定继续吗？";
					showConfirm(content);
					/*if(window.confirm(content)){
						checkNameResult = 1;
					}*/
				} else {
					/*showTip("号码未实名认证，不能充值");
					sj2();*/
					//var content = "<span style='color: red'>"+phone+"</span>未实名认证,金额:<span style='color: red'>"+realAccount+"</span>元，确定继续吗？";
					var content = "此号码未实名认证，确定继续充值吗？";
					showConfirm(content);
				}
			} else {
				showTip(data.ROOT.USER_MSG);
				sj2();
			}
		},
		error: function(textStatus) {
			showTip('服务器请求失败，请联系管理员！');
			sj2();
			console.info(textStatus);
		}
	});
};


var showConfirm = function(content){
	$("#nameVal").html(content);
	$('#my-confirm').modal({
		onConfirm: function(options) {
			callSaveOrder();
		},
		onCancel: function() {

		}
	});
};

//调用保存充值缴费支付订单
function callSaveOrder() {
	var params = getOrderParams();
	// console.log(params);
	if (params.rechargeMoney == "" || 0 == params.rechargeMoney) {
		showTip("请选择正常的充值金额");
		sj2();
		return;
	}
	$.ajax({
		type: "post",
		url: "../recharge/saveOrder",
		data: params,
		dataType: "json",
		headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
			console.info(data);
			if (data.resultCode == 1000) {
				$("#returnData").html(data.data);
			} else {
				showTip(data.message);
				sj2();
			}
			return;
		},
		error: function(textStatus) {
			showTip("服务器请求失败，请联系管理员！");
			sj2();
			console.info(textStatus);
		}
	});
}
function getOrderParams() {
	if (getParamValue("userId")) {
		userid = getParamValue("userId");
	}
	// console.log("userid = " + userid);
	var params = {};
	var realAccount = $(".chg-xianshi-num span").html();
	if (realAccount.indexOf("元") >= 0) {
		var size = realAccount.length;
		realAccount = realAccount.substring(0, size - 1);
	}
	//console.log(realAccount);
	params.captchaToken = $('#randcode').val(); //验证码
	params.orderId = $('#orderid').html(); //订单号
	params.rechargePhone = $('#phone').val().replace(/\s/g, ''); //缴费的手机号
	params.rechargeMoney = realAccount; //充值金额
	params.payAmount = 0.00; //支付金额，默认未支付
	params.payPlat = $("#pay-plat").val(); //支付平台，14-支付宝，15-建设银行，16-银联
	params.userId = userid; //营业员userId，新版本是由客户端传入，老版本是由fxstr解析得到
	params.saleType = getParamValue("saleType"); //营业员userId
	params.fxstr = getParamValue("fxstr"); //为了兼容老版本，需要解析该参数得到userId等参数
	return params;
}

//正则校验
function regularCheck(obj, patt) {
	if (obj && patt) {
		if (!patt.test(obj)) {
			return false;
		} else {
			return true;
		}
	} else {
		return false;
	}
}



//////////////////////////////////////////////////////////////////
//手机号码归属地查询
function payPhoneCheck_submit(data) {
	var flag = data[0].flag;
	var obj_div = data[0].obj_div;
	if ('0' == flag) { //非四川手机号
		document.getElementById("chg-bussy").style.display = "block";
		document.getElementById("chg-bussy").innerHTML = "请输入正确的四川移动手机号码";
		document.getElementById("phone").focus();
		sj2();
		return;
	} else if ('1' == flag) { //状态不正常
		//$("#"+obj_div).show().html("该号码状态不正常暂时不能交费");
		document.getElementById("chg-bussy").style.display = "block";
		document.getElementById("chg-bussy").innerHTML = "该号码状态不正常暂时不能交费";
		document.getElementById("phone").focus();
		sj2();
		return;
	} else {
		var isOk = true;
		isOk = (range_check(10, 500));
		if (!isOk) {
			document.getElementById("chg-bussy").style.display = "block";
			document.getElementById("chg-bussy").innerHTML = "充值金额输入错误，请重新输入在10和500元之间且是10元的倍数";
			sj2();
			return;
		} else {
			var bankType = '100100';
			var phone = $('#phone').val().replace(/\s/g, '');
			var realAccount = $(".chg-xianshi-num span").html();
			if (realAccount.indexOf("?") >= 0) {
				var size = realAccount.length;
				realAccount = realAccount.substring(0, size - 1);
			}
			//				alert("realAccount:"+realAccount);
			///var cost = realAccount*0.985;
			var cost = realAccount;
			var yzm = $('#randcode').val();
			var moduleId = request("moduleId");
			var share = request("share");
			var url = document.location.href;
			var fxstr = request("fxstr"); //url.split("?fxstr=")[1];
			var saleType = request("saleType");
			var CHANNELID = request("CHANNEL_ID");
			$.ajaxSubmit({
				page: 'chargeCenter',
				listener: 'channelsPaySubmit',
				artId: '',
				contentId: '',
				needCheck: false,
				needLoading: false,
				async: false,
				param: 'cond_PHONE_NO=' + phone + "&cond_BANK_TYPE=" + bankType + "&cond_REAL_ACCOUNT=" + realAccount + "&cond_COST=" + cost + "&cond_VERITY_CODE=" + yzm + "&cond_fxstr=" + fxstr + "&cond_CHANNEL_ID=" + CHANNELID + "&moduleId=" + moduleId + "&share=" + share + "&cond_saleType=" + saleType + "&payinfo=" + $('#payinfo').val(),
				afterFn: subOrderAfter
			});
		}
	}
}

//充值
function subOrderAfter(data) {
	if (data[0].error_message != null && data[0].error_message != '') {
		document.getElementById("chg-bussy").style.display = "block";
		document.getElementById("chg-bussy").innerHTML = data[0].error_message;
		sj2();
		//	    if(typeof(_tag)!="undefined"){_tag.dcsMultiTrack('DCS.dcsuri','/nopv.gif','WT.si.n','BL_o2ocz','WT.si_x','-99');}
		return;
	} else {
		//		if(typeof(_tag)!="undefined"){_tag.dcsMultiTrack('DCS.dcsuri','/nopv.gif','WT.si.n','BL_o2ocz','WT.si_x','99');}
		window.location.href = data[0].Target_Url;
	}
}

//充值金额大小校验
function range_check(min, max) {
	var val_obj = $(".chg-xianshi-num span").html();
	if (val_obj.indexOf("元") >= 0) {
		var size = val_obj.length;
		val_obj = val_obj.substring(0, size - 1);
		console.info(val_obj);
	}
	var msg = '';
	if (val_obj == null || val_obj.replace(/(^\s*)|(\s*$)/g, "") == "") {
		msg = '请输入' + min + '和' + max + '之间的整数！';
	}
	if (!isNaN(val_obj)) {
		var val = parseInt(val_obj);
		if (val < min || val > max) {
			msg = '请输入' + min + '和' + max + '之间的整数！';
		} else {
			var val_ = val % 10;
			if (val_ != 0) {
				msg = '请输入' + min + '和' + max + '之间10的倍数';
			}
		}
	}
	if (msg != '') {
		showTip(msg);
		sj2();
		return false;
	} else {
		return true;
	}
}

//接收URL参数，解析URL参数
function request(paras) {
	var url = location.href;
	var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
	var paraObj = {}
	for (i = 0; i < paraString.length; i++) {
		var j = paraString[i];
		paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
	}
	var returnValue = paraObj[paras.toLowerCase()];
	if (typeof(returnValue) == "undefined") {
		return "";
	} else {
		return returnValue;
	}
}


function setCookie(c_name, value, expire) {
	var c_login = c_name + "=" + value;
	if (expire) {
		c_login += "; expires=" + expire.toGMTString();
	}
	document.cookie = c_login;
}

function changePayPlat(obj, plat) {
	$obj = $(obj);
	var border = $obj.attr("style").indexOf("border");
	if (border != (-1)) {
		var $siblings = $obj.parent().parent().siblings();
		if ($obj.css("border").indexOf("none") != (-1)) {
			$obj.css({
				"border": "1px solid #01A0EB"
			});
			$obj.siblings("i").show();
			$siblings.find("img").css({
				"border": "none"
			});
			$siblings.find("i").hide();
		} else {
			$obj.css({
				"border": "none"
			});
			$obj.siblings("i").hide();
			$siblings.find("img").css({
				"border": "1px solid #01A0EB"
			});
			$siblings.find("i").show();
		}
	}

	$("#pay-plat").val(plat);
}